package com.ecnu.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ecnu.common.constant.HttpStatus;
import com.ecnu.common.core.domain.AjaxResult;
import com.ecnu.common.core.domain.entity.SysRole;
import com.ecnu.common.core.domain.entity.SysUser;
import com.ecnu.common.core.domain.model.LoginUser;
import com.ecnu.common.core.page.PageDomain;
import com.ecnu.common.core.page.TableDataInfo;
import com.ecnu.common.exception.ServiceException;
import com.ecnu.common.utils.*;
import com.ecnu.common.utils.http.UrlUtils;
import com.ecnu.common.utils.uuid.IdUtils;
import com.ecnu.system.domain.*;
import com.ecnu.system.domain.dto.*;
import com.ecnu.system.domain.vo.ProjectAllVO;
import com.ecnu.system.domain.vo.ProjectIntroductionVO;
import com.ecnu.system.domain.vo.ProjectListVO;
import com.ecnu.system.domain.vo.projectForMyVO;
import com.ecnu.system.mapper.*;
import com.ecnu.system.service.IProjectExcellentService;
import com.ecnu.system.service.IProjectService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * ecnu_活动表 服务实现类
 * </p>
 *
 * @author zdn
 * @since 2025-03-19
 */
@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements IProjectService {
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private ProjectTeacherMapper projectTeacherMapper;
    @Autowired
    private ProjectUserMapper projectUserMapper;
    @Autowired
    private ProjectIndexFileMapper indexFileMapper;
    @Autowired
    private ProjectStageMissionMapper stageMissionMapper;
    @Autowired
    private IProjectExcellentService excellentService;
    @Autowired
    private ProjectRangeMapper rangeMapper;

    /**
     * 分页查询
     */
    protected void startPage(PageDomain pageDomain) {
        PageUtils.startPage(pageDomain);
    }

    protected String getId() {
        return IdUtils.fastSimpleUUID();
    }


    protected TableDataInfo getDataTable(List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        rspData.setPageNum(new PageInfo(list).getPageNum());
        rspData.setPageSize(new PageInfo(list).getPageSize());
        return rspData;
    }

    @Override
    public TableDataInfo ProjectList(ProjectListDTO listDTO, LoginUser user) {
        try {
            if (listDTO.getSortingType().equals("推荐")) {
                TableDataInfo list = excellentService.list(listDTO);
                return list;
            }
            startPage(listDTO.getPageDomain());
            Long roleId = user.getUser() != null ? user.getUser().getRoles().get(0).getRoleId() : null;
            //获取分页项目
            List<ProjectListVO> listVOPage = projectMapper.selectListByType(listDTO, user, roleId);
            if (listVOPage.isEmpty()) {
                return getDataTable(listVOPage);
            }
            //获取活动负责人
            List<String> projectIds = listVOPage.stream()
                    .map(ProjectListVO::getId)
                    .collect(Collectors.toList());

            // 批量查询所有项目的负责人

            List<ProjectTeacher> projectTeachers = projectTeacherMapper.selectListForSysUserList(projectIds);

            // 将负责人按项目 id 分组
            Map<String, List<ProjectTeacher>> projectTeachersMap = projectTeachers.stream()
                    .collect(Collectors.groupingBy(ProjectTeacher::getProId));
            // 为每个项目设置负责人
            listVOPage.forEach(projectListVO -> {
                List<ProjectTeacher> teachers = projectTeachersMap.get(projectListVO.getId());
                String userVOs = teachers != null ?
                        teachers.stream()
                                .map(ProjectTeacher::getTeachName) // 提取 teachName
                                .collect(Collectors.joining(", ")) : // 用逗号拼接
                        "";
                projectListVO.setTeacher(userVOs);
            });
            //活动添加活动类型
            listVOPage.forEach(projectListVO -> {
                projectListVO.setProjectType(getProjectType(projectListVO));
            });
            return getDataTable(listVOPage);
        } catch (Exception e) {
            log.error("查询失败", e);
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.ERROR);
            rspData.setMsg("查询失败");
            return rspData;
        }
    }


    /**
     * 获取活动类型
     *
     * @param project
     * @return
     */
    public String getProjectType(ProjectListVO project) {
        Date date = new Date();

        if ("1".equals(project.getRegistrationType())) { // 使用常量前置避免空指针
            if (date.after(project.getRegistrationStartTime()) && date.before(project.getRegistrationEndTime())) {
                return "报名中";
            }
            if (date.after(project.getRegistrationEndTime()) && date.before(project.getStartTime())) {
                return "报名结束";
            }
        }

// 活动状态判断（无论是否需要报名）
        if (date.after(project.getStartTime()) && date.before(project.getEndTime())) {
            return "活动进行中";
        }
        if (date.after(project.getEndTime())) {
            return "活动结束";
        }

// 默认返回
        return "未开始";
    }

    @Override
    @Transactional
    public AjaxResult edit(ProjectDTO project, LoginUser userId) throws JsonProcessingException {
        if (project.getStartTime().after(project.getEndTime())) {
            return AjaxResult.error("开始时间不能晚于结束时间");
        }
        if (StringUtils.isBlank(project.getId())) {
            return saveProject(project, userId);//添加
        } else {
            return updateProject(project, userId);//修改
        }
    }

    @Override
    public TableDataInfo allList(ProjectListDTO listDTO, String name) {
        try {
            startPage(listDTO.getPageDomain());
            //获取分页项目
            List<ProjectAllVO> listVOPage = projectMapper.allListByName(listDTO, name);
            //可见范围查询
            List<ProjectRange> projectRanges = rangeMapper.selectList(null);
            listVOPage.forEach(projectListVO -> {
                projectListVO.setIsRangeName(projectRanges.stream()
                        .filter(projectRange -> projectRange.getId().equals(projectListVO.getIsRange()))
                        .findFirst()
                        .map(ProjectRange::getName)
                        .orElse(""));
                projectListVO.setIsReview(projectListVO.getIsRange().equals("1")?false:true);
            });
//            for (ProjectAllVO projectAllVO : listVOPage) {
//                List<UserDto> parsedList = JSON.parseObject(
//                        projectAllVO.getChargePerson(),
//                        new TypeReference<List<UserDto>>() {});
//
//                projectAllVO.setChargePersonList(parsedList==null?new ArrayList<>():parsedList);
//            }

            return getDataTable(listVOPage);
        } catch (Exception e) {
            log.error("查询失败", e);
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.ERROR);
            rspData.setMsg("查询失败");
            return rspData;
        }
    }

    @Override
    public AjaxResult infoById(String id) {
        ProjectDTO dto = new ProjectDTO();
        Project project2 = projectMapper.selectOne(
                new QueryWrapper<Project>()
                        .eq("id", id)
                        .eq("del_flag", "0"));
        if (project2 == null) {
            return AjaxResult.error("活动不存在");
        }
        BeanUtils.copyProperties(project2, dto);
//        dto.setChargePersonList( JSON.parseObject(
//                project2.getChargePerson(),
//                new TypeReference<List<UserDto>>() {}));
        // 负责人
        ProjectTeacher projectTeacher = new ProjectTeacher();
        projectTeacher.setProId(id);
//        projectTeacher.setDelFlag("0");
        List<ProjectTeacher> teachers = projectTeacherMapper.selectListForSysUser(projectTeacher);
        if (!teachers.isEmpty()) {
            dto.setTeacherList(teachers.stream()
                    .map(teacher -> {
                        UserDto userDto = new UserDto();
                        userDto.setId(teacher.getTechId());
                        userDto.setUsername(teacher.getTeachName());
                        return userDto;
                    })
                    .collect(Collectors.toList())
            );
        } else {
            dto.setTeacherList(new ArrayList<>());
        }
        // 成员
        List<ProjectUser> users = projectUserMapper.selectList(
                new LambdaUpdateWrapper<ProjectUser>()
                        .eq(ProjectUser::getProId, id)
                        .eq(ProjectUser::getDelFlag, "0"));
        if (!users.isEmpty()) {
            dto.setUserList(users.stream()
                    .map(user -> {
                        UserDto userDto = new UserDto();
                        userDto.setId(user.getUserId()); // 根据实际字段名调整
                        userDto.setUsername(user.getUserName()); // 根据实际字段名调整
                        return userDto;
                    })
                    .collect(Collectors.toList())
            );
        } else {
            dto.setUserList(new ArrayList<>());
        }

        ArrayList<ProjectIndexFileDTO> indexFileDTOList = new ArrayList<>();
        //获取活动资料
        List<ProjectIndexFile> projectFiles = indexFileMapper.selectList(
                new LambdaQueryWrapper<ProjectIndexFile>()
                        .eq(ProjectIndexFile::getProId, id)
                        .eq(ProjectIndexFile::getDelFlag, "0")
                        .orderByAsc(ProjectIndexFile::getSize)

        );
        if (projectFiles.size() != 0) {
            for (ProjectIndexFile projectFile : projectFiles) {
                ProjectIndexFileDTO indexFileDTO = new ProjectIndexFileDTO();
                BeanUtils.copyProperties(projectFile, indexFileDTO);
                indexFileDTO.setFullurl(UrlUtils.getUrl()  + indexFileDTO.getUrl());
                indexFileDTOList.add(indexFileDTO);
            }
        }
        dto.setInformations(indexFileDTOList);


        return AjaxResult.success(dto);
    }

//    public String getUrl() {
//        HttpServletRequest request = ServletUtils.getRequest();
//        return getDomain(request);
//    }
//
//    public static String getDomain(HttpServletRequest request) {
//        StringBuffer url = request.getRequestURL();
//        String contextPath = request.getServletContext().getContextPath();
//        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
//    }

    @Override
    public AjaxResult briefById(String id, LoginUser loginUser) {
        ProjectIntroductionVO dto = new ProjectIntroductionVO();
        Project project2 = projectMapper.selectOne(
                new QueryWrapper<Project>()
                        .eq("id", id)
                        .eq("del_flag", "0"));
        if (project2 == null) {
            return AjaxResult.error("活动不存在");
        }
        //添加权限限制
        if(!project2.getIsRange().equals("3")){
            List<SysRole> roles = loginUser.getUser().getRoles();
            String name = roles.stream()
                    .anyMatch(role -> role.getRoleId() != 1 && role.getRoleId()!=2)
                    ? loginUser.getUser().getUserId().toString() : null;
            if (StringUtils.isNotBlank( name)) {
                if (loginUser.getUserId()==null) {
                    return AjaxResult.error("请登录");
                }
                SysUser user = loginUser.getUser();
//                boolean isAdmin = !String.valueOf(user.getUserId()).equals(project2.getRangeType());
//                Boolean isReview = !String.valueOf(user.getDeptId()).equals(project2.getRangeType());
                if (!String.valueOf(user.getUserId()).equals(project2.getRangeType())
                        && !String.valueOf(user.getDeptId()).equals(project2.getRangeType())) {
                    return AjaxResult.error("没有权限");
                }
            }
        }
        //处理超链接是不是包含研学地址
        hrefUpdate(project2,loginUser);
        BeanUtils.copyProperties(project2, dto);
        //获取是否是报名逻辑
        if (project2.getRegistrationType().equals("1")) {
            dto.setRegistrationTime(
                    DateUtils.dateToString(project2.getRegistrationStartTime(), DateUtils.中文)
                            + "至" + DateUtils.dateToString(project2.getRegistrationEndTime(), DateUtils.中文));
        }
        //获取阶段
        QueryWrapper<ProjectStageMission> stage_id = new QueryWrapper<>();
        stage_id.eq("stage_id", dto.getId());
        stage_id.eq("del_flag", "0");
        stage_id.orderByAsc("sort", "create_time");
        List<ProjectStageMission> missionList = stageMissionMapper.selectList(stage_id);
        if (missionList != null && !missionList.isEmpty()) {
            dto.setStageList(missionList.stream()
                    .map(mission -> {
                        Map<String, Object> map = new HashMap<>();
                        map.put("name", mission.getMissionName());
                        map.put("timeInterval", DateUtils.dateToString(mission.getStartTime(), DateUtils.点号)
                                + " -- "
                                + DateUtils.dateToString(mission.getEndTime(), DateUtils.点号));
                        return map;
                    })
                    .collect(Collectors.toList())
            );
        }
        //补充--是否是管理员授课老师，是否报名学生（显示后续显示内容）
        if (loginUser.getUserId() != null) {
            boolean isUnauthorizedRole = loginUser.getUser().getRoles().stream()
                    .noneMatch(role -> role.getRoleId() != 1L && role.getRoleId()!=2L);
            if (isUnauthorizedRole) {
                dto.setIsSign(true);
            } else {
                List<ProjectTeacher> projectTeachers = projectTeacherMapper.selectList(
                        new LambdaQueryWrapper<ProjectTeacher>()
                                .eq(ProjectTeacher::getTechId, loginUser.getUserId())
                                .eq(ProjectTeacher::getProId, project2.getId())
                                .eq(ProjectTeacher::getDelFlag, "0")
                );
                if ((projectTeachers != null && !projectTeachers.isEmpty())||dto.getCreateUser().equals(String.valueOf(loginUser.getUserId()))) {
                    dto.setIsSign(true);
                }else {
                    List<ProjectUser> projectUsers = projectUserMapper.selectList(
                            new LambdaQueryWrapper<ProjectUser>().eq(ProjectUser::getUserId, loginUser.getUserId())
                                    .eq(ProjectUser::getProId, project2.getId())
                                    .eq(ProjectUser::getStatus,"0")
                    );
                    if (projectUsers != null && !projectUsers.isEmpty()) {
                        dto.setIsSign(true);
                    }
                }
            }
        }
        ArrayList<ProjectIndexFileDTO> indexFileDTOList = new ArrayList<>();
        //获取活动资料
        List<ProjectIndexFile> projectFiles = indexFileMapper.selectList(
                new LambdaQueryWrapper<ProjectIndexFile>()
                        .eq(ProjectIndexFile::getProId, id)
                        .eq(ProjectIndexFile::getDelFlag, "0")
                        .orderByAsc(ProjectIndexFile::getSize)
        );
        if (projectFiles.size() != 0) {
            for (ProjectIndexFile projectFile : projectFiles) {
                ProjectIndexFileDTO indexFileDTO = new ProjectIndexFileDTO();
                BeanUtils.copyProperties(projectFile, indexFileDTO);
                indexFileDTO.setFullurl(UrlUtils.getUrl() + indexFileDTO.getUrl());
                indexFileDTOList.add(indexFileDTO);
            }
        }
        dto.setInformations(indexFileDTOList);
        return AjaxResult.success(dto);
    }

    private void hrefUpdate(Project project2, LoginUser loginUser) {
        try {
            if (loginUser.getUserId()!=null&&project2.getTitle()!=null) {
                String extracted =OtherUtil.extracted(project2.getTitle(), loginUser,project2.getId(), project2.getProType());
                project2.setTitle(extracted);
            }

        }catch (Exception e){
            log.error("知网解析失败:"+e.getMessage());
            throw new ServiceException(e.getMessage(),HttpStatus.ACCEPTED);
        }

    }

    @Override
    public TableDataInfo projectForMy(ProjectForMyDTO project, String userId) {
        //学生查询自己参加的活动
        List<projectForMyVO> list1 = projectMapper.selectForProject(project, userId);
        //教师查询自己参加的活动
        List<projectForMyVO> list2 = projectMapper.selectForProjectTeacher(project, userId);
        if (list2 != null && !list2.isEmpty()) {
            list1.addAll(list2);
        }

        startPage(project.getDomain());

        List<projectForMyVO> list = OtherUtil.memoryPage(new ArrayList<>(new LinkedHashSet<>(list1))
                , project.getDomain().getPageSize()
                , project.getDomain().getPageNum());
        if (list == null || list.isEmpty()) {
            return OtherUtil.tableSuccess(list);
        }

        //取list的活动id
        for (projectForMyVO vo : list) {
            if (vo.getStartTime() != null && vo.getEndTime() != null) {
                vo.setStartEndTime(DateUtils.dateToString(vo.getStartTime(), DateUtils.中文)
                        + "至" + DateUtils.dateToString(vo.getEndTime(), DateUtils.中文));
            }
            if (new Date().before(vo.getStartTime())) {
                vo.setStatus("筹备中");
            } else if (vo.getEndTime() != null && new Date().after(vo.getEndTime())) {
                vo.setStatus("已完成");
            } else {
                vo.setStatus("进行中");
            }
            //根据活动id，教师名字，取对应学生的名字
            if (StringUtils.isNotBlank(vo.getTeacherName())) {
                LambdaQueryWrapper<ProjectUser> eq = new LambdaQueryWrapper<ProjectUser>()
                        .eq(ProjectUser::getProId, vo.getId())
                        .eq(ProjectUser::getDelFlag, "0")
                        .eq(ProjectUser::getStatus,"0")
                        .eq(ProjectUser::getTeacherName, vo.getTeacherName())
                        .groupBy(ProjectUser::getUserId);

                List<ProjectUser> projectUsers = projectUserMapper.selectList(eq);
                String result = projectUsers.stream()
                        .map(ProjectUser::getUserName)
                        .filter(StringUtils::isNotBlank)
                        .collect(Collectors.joining("、"));

                vo.setOtherStd(StringUtils.defaultIfBlank(result, "无"));
            }else {
                vo.setOtherStd("无");
            }
        }
        if (StringUtils.isNotBlank(project.getStatus())) {
            list = list.stream()
                    .filter(item -> item.getStatus().equals(project.getStatus()))
                    .collect(Collectors.toList());
        }
//        long total = new PageInfo(list1).getTotal();
        return OtherUtil.tableSuccess2(list, new PageInfo(list1).getTotal());
    }

    private AjaxResult updateProject(ProjectDTO project, LoginUser user) throws JsonProcessingException {
        Project project2 = projectMapper.selectOne(
                new QueryWrapper<Project>()
                        .eq("id", project.getId())
                        .eq("del_flag", "0"));
        if (project2 == null) {
            return AjaxResult.error("活动不存在");
        }
        Project project1 = new Project();
        List<ProjectTeacher> teachers;
        List<ProjectUser> users;
        //修改
        BeanUtils.copyProperties(project, project1);
        if(!project.getIsRange().equals(project2.getIsRange())){//前后状态改变
            project1.setRangeType(String.valueOf(user.getUserId()));//把可见范围改成自己ID
        }else {
            project1.setIsRange(project2.getIsRange());
        }
        if (project1.getIsRange().equals("1")) {
            project1.setRangeType(project2.getCreateUser());
        }
        project1.setUpdateUser(String.valueOf(user.getUserId()));
        ObjectMapper objectMapper = new ObjectMapper();
//        project1.setChargePerson(project.getChargePersonList() == null ? "[]" : objectMapper.writeValueAsString(project.getChargePersonList()));//任务清单==>list转成string

        if (project.getEndTime() != null) {
            project1.setEndTime(OtherUtil.getEndOfDay(project.getEndTime()));
        }
        if (project.getRegistrationEndTime() != null) {
            project1.setRegistrationEndTime(OtherUtil.getEndOfDay(project.getRegistrationEndTime()));
        }
        int insert = projectMapper.updateById(project1);
        if (insert == 0) {
            return AjaxResult.error("活动添加失败");
        }
        //添加主持人/主办方/负责人
        if (project.getTeacherList() != null && !project.getTeacherList().isEmpty()) {
            projectTeacherMapper.update(null,
                    new LambdaUpdateWrapper<ProjectTeacher>()
                            .eq(ProjectTeacher::getProId, project.getId())
                            .set(ProjectTeacher::getDelFlag, "2"));
            teachers = project.getTeacherList().stream()
                    .map(userDto -> {
                        ProjectTeacher teacher = new ProjectTeacher();
                        teacher.setId(getId());
                        teacher.setTechId(userDto.getId());
                        teacher.setTeachName(userDto.getUsername());
                        teacher.setProId(project1.getId());
                        return teacher;
                    })
                    .collect(Collectors.toList());
            insert = projectTeacherMapper.insertBatch(teachers);
            if (insert == 0) {
                return AjaxResult.error("活动负责人添加失败");
            }
        }//修改逻辑，如果不选任何人的话去除提供的权限，只能创建者能看
        else {
            ProjectTeacher teacher = new ProjectTeacher();
//            teacher.setProId(project1.getId());
            teacher.setDelFlag("2");
            projectTeacherMapper.update(teacher,
                    new LambdaUpdateWrapper<ProjectTeacher>()
                            .eq(ProjectTeacher::getProId, project.getId()));
        }
        //添加成员
        if (project.getUserList() != null && !project.getUserList().isEmpty()) {
            projectUserMapper.update(null,
                    new LambdaUpdateWrapper<ProjectUser>()
                            .eq(ProjectUser::getProId, project.getId())
                            .set(ProjectUser::getDelFlag, "2"));
            users = project.getUserList().stream()
                    .map(userDto -> {
                        ProjectUser user1 = new ProjectUser();
                        user1.setId(getId());
                        user1.setUserId(userDto.getId());
                        user1.setUserName(userDto.getUsername());
                        user1.setProId(project1.getId());
                        return user1;
                    })
                    .collect(Collectors.toList());
            insert = projectUserMapper.insertBatch(users);
            if (insert == 0) {
                return AjaxResult.error("活动成员添加失败");
            }
        }
        if (project.getInformations() != null && !project.getInformations().isEmpty()) {
            indexFileMapper.update(null,
                    new LambdaUpdateWrapper<ProjectIndexFile>()
                            .eq(ProjectIndexFile::getProId, project.getId())
                            .set(ProjectIndexFile::getDelFlag, "2"));
            Integer count = 1;
            for (ProjectIndexFileDTO projectFile : project.getInformations()) {
                ProjectIndexFile indexFile = new ProjectIndexFile();
                BeanUtils.copyProperties(projectFile, indexFile);
                indexFile.setId(getId());
                indexFile.setProId(project1.getId());
                indexFile.setCreateUser(String.valueOf(user.getUserId()));
                indexFile.setSize(count);
                indexFileMapper.insert(indexFile);
                if (count <= project.getInformations().size()) {
                    count++;
                }
            }
        }
        return AjaxResult.success(project1.getId());
    }

    private AjaxResult saveProject(ProjectDTO project, LoginUser user) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        Project project1 = new Project();
        List<ProjectTeacher> teachers = new ArrayList<>();
        List<ProjectUser> users = new ArrayList<>();
        //新增活动
        BeanUtils.copyProperties(project, project1);
        project1.setId(getId());
        project1.setCreateUser(String.valueOf(user.getUserId()));
        project1.setRangeType(String.valueOf(user.getUserId()));//自己可见
//        project1.setChargePerson(project.getChargePersonList() == null ? "[]" : objectMapper.writeValueAsString(project.getChargePersonList()));//任务清单==>list转成string
        if (project.getEndTime() != null) {
            project1.setEndTime(OtherUtil.getEndOfDay(project.getEndTime()));
        }
        if (project.getRegistrationEndTime() != null) {
            project1.setRegistrationEndTime(OtherUtil.getEndOfDay(project.getRegistrationEndTime()));
        }

        int insert = projectMapper.insert(project1);
        if (insert == 0) {
            return AjaxResult.error("活动添加失败");
        }

//        Map<String, ProjectTeacher> teacherMap = new LinkedHashMap<>();
        List<UserDto> teacherList = project.getTeacherList();
//        UserDto userDto1 = new UserDto();
//        userDto1.setId(String.valueOf(user.getUserId()));
//        userDto1.setUsername(user.getUsername());
//        teacherList.add(userDto1);
        //添加主持人/主办方/负责人
        if (teacherList != null && !teacherList.isEmpty()) {
            //            }
            teachers = teacherList.stream()
                    .filter(Objects::nonNull)
                    .filter(b -> b.getId() != null && !b.getId().isEmpty())
                    .map(a -> {
                        ProjectTeacher teacher = new ProjectTeacher();
                        teacher.setId(getId());
                        teacher.setTechId(a.getId());
                        teacher.setTeachName(a.getUsername());
                        teacher.setProId(project1.getId());
                        return teacher;
                    })
//                    .filter(teacher -> teacherMap.put(teacher.getTechId(), teacher) == null)
                    .collect(Collectors.toList());
            insert = projectTeacherMapper.insertBatch(teachers);
            if (insert == 0) {
                return AjaxResult.error("活动负责人添加失败");
            }
        }
        //添加成员
        if (project.getUserList() != null && !project.getUserList().isEmpty()) {
            users = project.getUserList().stream()
                    .map(userDto -> {
                        ProjectUser user1 = new ProjectUser();
                        user1.setId(getId());
                        user1.setUserId(userDto.getId());
                        user1.setUserName(userDto.getUsername());
                        user1.setProId(project1.getId());
                        return user1;
                    })
                    .collect(Collectors.toList());
            insert = projectUserMapper.insertBatch(users);
            if (insert == 0) {
                return AjaxResult.error("活动成员添加失败");
            }
        }

        //添加活动文件
        if (project.getInformations() != null && !project.getInformations().isEmpty()) {
            int cont = 1;
            for (ProjectIndexFileDTO projectFile : project.getInformations()) {
                ProjectIndexFile indexFile = new ProjectIndexFile();
                BeanUtils.copyProperties(projectFile, indexFile);
                indexFile.setId(getId());
                indexFile.setSize(cont);
                indexFile.setProId(project1.getId());
                indexFile.setCreateUser(String.valueOf(user.getUserId()));
                indexFileMapper.insert(indexFile);
                int size = project.getInformations().size();
                if (cont <= size) {
                    cont++;
                }
            }
        }
        return AjaxResult.success(project1.getId());
    }

}
